package com.example.administrator.commonlibrary.wholehelper;



import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;

import com.example.administrator.commonlibrary.R;
import com.example.administrator.commonlibrary.utils.LogUtil;

/**
 * @author wang_hong_wei
 * @description ProgressDialog 的帮助类
 * @Date 2018-5-11
 */
public class LoadingDialogHelper {

    private static LoadingDialogHelper progressDialogHelper = new LoadingDialogHelper();
    private AlertDialog alertDialog;

    public static LoadingDialogHelper getInstance(){
        return  progressDialogHelper;
    }

    /**
     * 创建 AlertDialog
     */
    public  AlertDialog createDialog(Context context) {
        if (null == alertDialog) {
            alertDialog = createAlertDialog(context);
        } else if (context != alertDialog.getContext()) {
            LogUtil.d("此处引发窗体泄露 | orign context -> " + alertDialog.getContext() + " | now context -> " + context);
            dismissDialog();
            alertDialog = createAlertDialog(context);
        }
        return alertDialog;
    }

    /**
     * 释放 AlertDialog
     */
    private  void dismissDialog() {
        if (null == alertDialog) {
            return;
        }
        if (alertDialog.isShowing()) {
            try {
                alertDialog.cancel();
                alertDialog = null;
            } catch (Exception e) {
                LogUtil.printStackTrace(e);
            }
        }else {
            alertDialog = null;
        }
    }


    private  AlertDialog createAlertDialog(Context context) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(context,R.style.app_loading_theme);
        dialog.setCancelable(true);//设置点击框外，不可以消失，home 键也不可以消失
        AlertDialog alertDialog = dialog.create();
        alertDialog.setCanceledOnTouchOutside(false);//设置点击框外，不可以消失，但是home 键可以
        alertDialog.getWindow().setGravity(Gravity.CENTER);
        return alertDialog;
    }
}
